<template>
    <van-nav-bar title="商品分类" />
  
    <van-tree-select v-model:main-active-index="active" 
    height="100vh" 
    :items="items" 
    @click-nav="onselect">
      <template #content>
        <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <!-- 加载列表 -->
    <van-list 
            v-model:loading="loading"
            :finished="finished"
            :offset="10"
            finished-text="没有更多了" @load="onLoad">
<div v-for="item in list">
        <van-card
          :price="item.price"
          :desc="item.content"
          :title="item.name"
          :thumb="item.thumbs_cdn"
        >
          <template #num>
            <van-button size="mini" @click="ProductInfo(item.id)">查看详情</van-button>
          </template>
        </van-card>
</div>
        </van-list>
      </van-pull-refresh>
      </template>
    </van-tree-select>
  
    <Tabbar />
  </template>
  
  <script setup>
    const {proxy} = getCurrentInstance()

    const active = ref(0)
    let items = reactive([{text: '全部分类', value: '0'},])

    const refreshing = ref(false);
    const finished = ref(false);
    const loading = ref(false);
    const list = ref([]);
    const page = ref(1);
    const num =ref(0)

    onBeforeMount(() => {
      getTypeData();
    });

    const onRefresh = () =>
{
    list.value = [];
    page.value = 1;
    loading.value = true;
    finished.value = false;
    refreshing.value = true;

    setTimeout(onLoad,1500);
}


    const getTypeData =async () =>
    {
      let result = await proxy.$http.post({
        url:'/product/type'
      });

      if(result.code === 1){
        for(let item of result.data)
        {
          items.push({
                text:item.name,
                value:item.id
          })
        }
      }
    }

    const onLoad = async () =>
    {
      if(refreshing.value)
    {
        refreshing.value = false;
    }
      let params = {
        typeid:num.value,
        page:page.value,
    }
   

    let result = await proxy.$http.post({
        url:'/product/index',
        params
    })
    
    finished.value = false;
    loading.value = false;


    if(result.code === 1)
    {
        list.value = list.value.concat(result.data.list);
        let count = result.data.count ?? 0;

        if(list.value.length >= count)
        {
            finished.value = true;
            return false;
        }

        page.value = page.value + 1;
    }else{
        finished.value = true;
        proxy.$warning(result.msg);
    }
    }

    const onselect = (select) =>
    {
      items.forEach((value, index) => {
        
        if(select == index)
        {
          num.value = value['value'];
        }
    });

    
    onRefresh();
      
    }
  
    const ProductInfo = (id) => proxy.$router.push({path:'/product/info',query:{proid:id}})
  </script>